package com.szholly.plug.activity.interceptor.reminders;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.szholly.plug.activity.model.BpmConfigCache;
import com.szholly.plug.activity.model.BpmConfigRow;
import com.szholly.plug.activity.model.BpmTaskConfigRow;
import com.szholly.plug.activity.model.BpmWorklistRow;
import com.szholly.plug.activity.model.BpmWorklistTable;
import com.szholly.utils.common.notice.IEmailNotice;
import com.szholly.utils.common.notice.IPhoneNotice;
import com.szholly.utils.common.notice.ISystemNotice;
import com.szholly.utils.spring.SpringBeanFactory;
import com.szholly.utils.util.DateUtil;
import com.szholly.utils.util.DateUtils;
import com.szholly.utils.util.StringUtils;
import com.szholly.data.general.IQueryMap;
import com.szholly.data.general.QueryMap;
import com.szholly.plug.safe.entity.user.UserEntity;
import com.szholly.plug.safe.entity.user.UserService;

/**
 * 定义催办任务
 */
@Component
public class RemindersTask {
	
	private ISystemNotice systemNotice;
	private IEmailNotice emailNotice;
	private IPhoneNotice phoneNotice;

	private ISystemNotice getSystemNotice() {
		if (systemNotice == null) {
			systemNotice = (ISystemNotice) SpringBeanFactory
					.getBean(ISystemNotice.class);
		}
		return systemNotice;
	}

	private IEmailNotice getEmailNotice() {
		if (emailNotice == null) {
			emailNotice = (IEmailNotice) SpringBeanFactory
					.getBean(IEmailNotice.class);
		}
		return emailNotice;
	}

	private IPhoneNotice getPhoneNotice() {
		if (phoneNotice == null) {
			phoneNotice = (IPhoneNotice) SpringBeanFactory
					.getBean(IPhoneNotice.class);
		}
		return phoneNotice;
	}
	
	/**
	 * 1小时处理一次
	 */
	@Scheduled(cron = "0 0 0/1 * * *")
	public void runTask(){
		
		IQueryMap queryMap = new QueryMap();
		HashMap<String, String> map = new HashMap<String, String>();
		map.put(BpmWorklistRow.FIELD_HASCJREMINDERS, "1");
		map.put(BpmWorklistRow.FIELD_HASWCREMINDERS, "1");
		queryMap.getWhereMap().put("or", map);
		
		List<BpmWorklistRow> workList = 
				BpmWorklistTable.getSingleRef().getEntityList(BpmWorklistRow.class, queryMap);
		if(workList==null || workList.size()<=0){
			return;
		}
		
		List<BpmWorklistRow> saveList = new ArrayList<BpmWorklistRow>();
		for(BpmWorklistRow work : workList){
			String taskDefinitionKey = work.getTaskDefinid();
			BpmConfigRow configRow =  BpmConfigCache.getConfig(work.getSDefinid());
			BpmTaskConfigRow configTaskRow = BpmConfigCache.getTaskConfig(work.getSDefinid(), taskDefinitionKey);
			if(configTaskRow==null){
				continue;
			}
			
			// 超时时间
			String sx = configTaskRow.getRemindersQx();
			// 创建时间
			String cjsj = configTaskRow.getRemindersCj();
			// 到期时间
			String wcqx = configTaskRow.getRemindersWc();
			// 通知模板
			String body = configTaskRow.getRemindersMb();
			if(StringUtils.IsNullOrSpace(configTaskRow.getRemindersQy())
					|| !configTaskRow.getRemindersQy().equals("1")
					|| StringUtils.IsNullOrSpace(body)){
				continue;
			}
			
			String[] users = work.getSAssingusers().split(",");
			List<String> userList = new ArrayList<String>();
			for(int i=0;i<users.length;i+=2){
				userList.add(users[i]);
			}
			
			// 创建时间
			if(!StringUtils.IsNullOrSpace(cjsj) && work.getHasCJReminders().equals("1")){
				long day = DateUtil.getDiffDayEx2(work.getDBegintime());
				long lCjsj = Long.parseLong(cjsj);
				if(day > lCjsj){
					for(String userId : userList){
						UserEntity to = getUser(userId);
						sendMsg(work, configRow, configTaskRow, to, body);
					}
					work.setHasCJReminders("");
					saveList.add(work);
				}
			}
			
			// 完成期限
			if(!StringUtils.IsNullOrSpace(wcqx) && !StringUtils.IsNullOrSpace(sx)
					&& work.getHasWCReminders().equals("1")){
				long day = DateUtil.getDiffDayEx2(work.getDBegintime());
				long lSx = Long.parseLong(sx);
				long lWcqx = Long.parseLong(wcqx);
				if(day > lSx - lWcqx){
					for(String userId : userList){
						UserEntity to = getUser(userId);
						sendMsg(work, configRow, configTaskRow, to, body);
					}
					work.setHasWCReminders("");
					saveList.add(work);
				}
			}
			
			String springName = configTaskRow.getTaskDdtz();
			if(!StringUtils.IsNullOrSpace(springName)){
				ICustomBpmReminders custom = (ICustomBpmReminders)SpringBeanFactory.getBean(springName);
				custom.taskOption(work, configRow, configTaskRow);
			}
		}
		BpmWorklistTable.getSingleRef().save(saveList);
	}
	
	private UserEntity getUser(String userId){
		IQueryMap queryMap = new QueryMap();
		queryMap.getWhereMap().put(UserEntity.FIELD_USERID, userId);
		return UserService.getSingleRef().getEntity(UserEntity.class, queryMap);
	}
	
	private void sendMsg(BpmWorklistRow work, BpmConfigRow configRow, 
			BpmTaskConfigRow configTaskRow, UserEntity to, String body) {
		body = body.replace("{BpmDefinitionName}", configRow.getSDefitionName()); // 工作流定义名称
		body = body.replace("{BpmGroupName}", configRow.getSGroup()); // 工作流所在分组名称
		body = body.replace("{TaskDefinitionName}", configTaskRow.getTaskName()); // 当前任务定义名称
		body = body.replace("{TaskTitle}", work.getBusiness()); // 流程任务的业务名称
		Date nowDate = new Date();
		body = body.replace("{TaskTime}", DateUtils.convertDateTimeToString(nowDate)); // 流程任务的处理时间
		String qx = configTaskRow.getRemindersQx();
		body = body.replace("{TaskSurplusTime}", qx); // 任务时限时间(小时)
		body = body.replace("{TaskEndTime}", DateUtils.convertDateTimeToString(nowDate)); // 任务时限时间
		
		// 系统通知
		if(!StringUtils.IsNullOrSpace(configTaskRow.getRemindersXt())
				&& configTaskRow.getNoticeXt().equals("1")){
			if(getSystemNotice()!=null){
				getSystemNotice().sendNotice(null, to, "系统通知", body);
			}
		}
		
		// EMail通知
		if(!StringUtils.IsNullOrSpace(configTaskRow.getRemindersEMail())
				&& configTaskRow.getNoticeEMail().equals("1")){
			if(getEmailNotice()!=null){
				getEmailNotice().sendNotice(null, to, "系统通知", body);
			}
		}
		
		// 电话通知
		if(!StringUtils.IsNullOrSpace(configTaskRow.getRemindersPhone())
				&& configTaskRow.getNoticePhone().equals("1")){
			if(getPhoneNotice()!=null){
				getPhoneNotice().sendNotice(null, to, "系统通知", body);
			}
		}
	}
}